from fastadmin.run import app
from fastadmin.config.config import *
from fastapi.middleware.cors import CORSMiddleware
from fastapi import Request
import os
import time
# 加载中间件,判断是否开启跨域
if CORS:
    origins = [
        "*"
    ]
    app.add_middleware(CORSMiddleware,
                       allow_origins = origins,
                       allow_credentials = True,
                       allow_methods = ["*"],
                       allow_headers = ["*"]
                       )

#加载全局中间件
router_directory = os.path.join(os.path.join(os.path.dirname(os.path.dirname(__file__)), "app"),"middleware.py")
if os.path.exists(router_directory):
    from fastadmin.app.middleware import middleware
    if middleware and len(middleware)>0:
        for m in middleware:
            app.add_middleware(m)



#加载动态中间件
@app.middleware("http")
async def load_app_init_middleware(request: Request,call_next):
    start_time = time.perf_counter()
    response = await call_next(request)
    process_time = time.perf_counter() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response